package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.WmTreadLoaclUtil.WmTreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    /**
     * 这是从header中获取到用户的id,之后利用Threadlocal方法存入到对应的实体类中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //因为在前面拦截器分析中,在header中加的就是userId,所以这个地方可以写死一个.
        String userId = request.getHeader("userId");
        if (userId!=null){
            WmUser wmUser = new WmUser();
            wmUser.setApUserId(Integer.valueOf(userId));
            //自己创建的,可以直接用
            WmTreadLocal.setUser(wmUser);
            log.info("wmTokenFilter设置用户信息到threadlocal中...");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
         WmTreadLocal.clear();
        log.info("清理threadlocal中的数据");
    }
}
